<template>
  <global-layout @dynamicRouterShow="dynamicRouterShow" @closeTabPage="closeTabPage">
    <contextmenu :itemList="menuItemList" :visible.sync="menuVisible" @select="onMenuSelect" />
    <a-tabs 
      @contextmenu.native="(e) => onContextmenu(e)"
      v-if="multipage"
      :active-key="activePage"
      class="tab-layout-tabs"
      style="height: 52px;position:relative;"
      :hide-add="true"
      type="editable-card"
      @change="changePage"
      @edit="editPage"
    >
      <a-tab-pane :id="page.fullPath" :key="page.fullPath" v-for="page in pageList">
        <span slot="tab" :pagekey="page.fullPath">{{ page.meta.title }}</span>
      </a-tab-pane>
    </a-tabs>
    <div style="position:relative;">
      <div class="ant-set-system-info" style="z-index:5;position:absolute;top:-38px;right:0px;color:#000;">
        <a-dropdown>
          <span class="action action-full ant-dropdown-link user-dropdown-menu">
            <a-icon type="setting" />
            <span> 设置</span>
          </span>
          <a-menu slot="overlay" class="user-dropdown-menu-wrapper">
            <a-menu-item key="10" @click="toggleBlogHome">
              <a-icon type="compass" />
              <span>我的主页</span>
            </a-menu-item>
            <a-menu-item key="10" @click="toggleBlogCenter">
              <a-icon type="crown" />
              <span>博客中心</span>
            </a-menu-item>
            <a-menu-item key="10" @click="toggleBlogPublish">
              <a-icon type="laptop" />
              <span>发布博客</span>
            </a-menu-item>
            <a-menu-item key="0">
              <router-link :to="{ name: 'account-center' }">
                <a-icon type="user" />
                <span>博文交流</span>
              </router-link>
            </a-menu-item>
            <a-menu-item key="1">
              <router-link :to="{ name: 'account-settings-base' }">
                <a-icon type="tool" />
                <span>账户设置</span>
              </router-link>
            </a-menu-item>
            <a-menu-item key="3" @click="systemSetting">
              <a-icon type="home" />
              <span>系统设置</span>
            </a-menu-item>
            <a-menu-item key="4" @click="updatePassword">
              <a-icon type="setting" />
              <span>密码修改</span>
            </a-menu-item>
            <a-menu-item key="5" @click="updateCurrentDepart">
              <a-icon type="cluster" />
              <span>切换部门</span>
            </a-menu-item>
            <a-menu-item key="7" @click="toggleTopMenu">
              <a-icon type="environment" />
              <span>显示顶部</span>
            </a-menu-item>
            <a-menu-divider />
            <a-menu-item key="9" @click="handleLogout">
              <a-icon type="logout" />
              <span>退出登录</span>
            </a-menu-item>
          </a-menu>
        </a-dropdown>
      </div>
    </div>
    <div style="margin: 12px 12px 0;position:relative;">
      <transition name="page-toggle">
        <keep-alive v-if="multipage">
          <router-view />
        </keep-alive>
        <router-view v-else />
      </transition>
      <div style="position:absolute;top:0p;">
      </div>
    </div>
  </global-layout>
</template>

<script>
import GlobalLayout from "@/components/page/GlobalLayout";
import Contextmenu from "@/components/menu/Contextmenu";
import { mixin, mixinDevice } from "@/utils/mixin.js";
import * as hashtoken from "@/api/hashToken/hashtoken.js";
import * as tools from "@/utils/util";

//Tab标题
const titleKV = () => window.titleKV;

export default {
  name: "TabLayout",
  components: {
    GlobalLayout,
    Contextmenu
  },
  mixins: [mixin, mixinDevice],
  data() {
    return {
      pageList: [],
      linkList: [],
      activePage: "",
      menuVisible: false,
      menuItemList: [
        { key: "1", icon: "arrow-left", text: "关闭左侧" },
        { key: "2", icon: "arrow-right", text: "关闭右侧" },
        { key: "3", icon: "close", text: "关闭其它" }
      ]
    };
  },
  computed: {
    multipage() {
      //判断如果是手机模式，自动切换为单页面模式
      if (this.isMobile()) {
        return false;
      } else {
        return this.$store.state.app.multipage;
      }
    },
    userInfo() {
      return this.$store.getters.userInfo;
    }
  },
  async created() {
    
    window.initLayout(this);

    setTimeout(() => {
      let rootUrl = window.sessionStorage.getItem(`system_root_url`);
      if(!(Object.is(rootUrl , '') || Object.is(rootUrl , null) || Object.is(rootUrl , undefined))){
        this.$router.push(`${rootUrl}`)
      }
    } , 150);

    await this.calculateToken();

  },
  watch: {
    $route: function(newRoute) {
      //设置Tab栏标题
      if (
        typeof titleKV()[newRoute.params.code] != "undefined" &&
        titleKV()[newRoute.params.code] != "" &&
        titleKV()[newRoute.params.code] != null
      ) {

        newRoute.meta.title = titleKV()[newRoute.params.code];
      }
      this.activePage = newRoute.fullPath;
      if (!this.multipage) {
        this.linkList = [newRoute.fullPath];
        this.pageList = [Object.assign({}, newRoute)];
      } else if (this.linkList.indexOf(newRoute.fullPath) < 0) {
        this.linkList.push(newRoute.fullPath);
        this.pageList.push(Object.assign({}, newRoute));
      } else if (this.linkList.indexOf(newRoute.fullPath) >= 0) {
        let oldIndex = this.linkList.indexOf(newRoute.fullPath);
        let oldPositionRoute = this.pageList[oldIndex];
        this.pageList.splice(
          oldIndex,
          1,
          Object.assign({}, newRoute, { meta: oldPositionRoute.meta })
        );
      }
    },
    activePage: function(key) {
      //获取激活Index
      var index = this.linkList.lastIndexOf(key);
      //获取激活对象
      var waitRouter = this.pageList[index];
      //获取拷贝对象
      var obj = Object.assign({}, waitRouter);
      //设置动态路由
      try {
        let tempKV = titleKV();
        if (obj && obj.params && obj.params.code && Object.hasOwnProperty.call(tempKV,obj.params.code) && tools.deNull([obj.params.code]) != "") {
          this.dynamicRouterShow(key, titleKV()[obj.params.code]);
        }
      } catch (error) {
        console.log(error);
      }
      //跳转到激活页面
      try {
        this.$router.push(obj.fullPath);
        //设置样式
        setTimeout(() => {
          $('.ant-tabs.ant-tabs-card .ant-tabs-tab').css('cssText', 'padding: 0px 12px !important; margin-right: 6px !important; ');
        } , 150);
      } catch (error) {
        console.log(error);
      }
    },
    multipage: function(newVal) {
      if (!newVal) {
        this.linkList = [this.$route.fullPath];
        this.pageList = [this.$route];
      }
    },
    
    $root: () => {}
  },
  methods: {
    ...Vuex.mapActions(["Logout"]),
    changePage(key) {
      this.activePage = key;
    },
    async calculateToken(){
      //计算缓存数据
      var cache = localStorage.getItem(`pro__Login_Username`);
      //计算hashtoken值
      var username = tools.isNull(cache) ? '' : JSON.parse(cache)['value'];
      var date = dayjs().format('YYYY-MM-DD');
      //查询缓存中的token
      var cachetoken = hashtoken.queryToken(date , username);
      //设置url token hashkey
      hashtoken.calcuToken(cachetoken.key, cachetoken.hash, date, username);
    },
    editPage(key, action) {
      this[action](key);
    },
    remove(key) {
      window.removeLayout(key , this);
    },
    onContextmenu(e) {
      window.onContextmenuLayout(e , this);
    },
    getPageKey(target, depth) {
      window.getPageKeyLayout(target , depth , this);
    },
    onMenuSelect(key, target) {
      window.onMenuSelectLayout(key , target , this);
    },
    closeOthers(pageKey) {
      window.closeOthersLayout(pageKey , this);
    },
    closeLeft(pageKey) {
      window.closeLeftLayout(pageKey, this);
    },
    closeRight(pageKey) {
      window.closeRightLayout(pageKey , this);
    },
    dynamicRouterShow(key, title) {
      window.dynamicRouterShowLayout(key, title, this);
    },
    closeTabPage(key) {
      window.closeTabPageLayout(key, this);
    },
    checkClosePageValid(key){
      window.closeTabLayout(key, this);
    },
    toggleTopMenu(){
      window.toggleTopMenuLayout(this);
    },
    updatePassword() {
      window.menuRefs.userPassword.show(window.menuRefs.userInfo().username);
    },
    updateCurrentDepart() {
      window.menuRefs.departSelect.show();
    },
    systemSetting() {
      window.menuRefs.settingDrawer.showDrawer();
    },
    handleLogout() {
      window.handleLogoutLayout(this);
    },
    toggleBlogHome() {
      this.$router.push(`/account/author/${window.menuRefs.userInfo().username}`);
    },
    toggleBlogCenter(){
      this.$router.push(`/blog/centerlist`);
    },
    toggleBlogPublish(){
      this.$router.push(`/blog/center`);
    },
  }
};
</script>

<style lang="scss" scoped>
.page-transition-enter {
  opacity: 0;
}
.page-transition-leave-active {
  opacity: 0;
}
.page-transition-enter .page-transition-container,
.page-transition-leave-active .page-transition-container {
  -webkit-transform: scale(1.1);
  transform: scale(1.1);
}
/*美化弹出Tab样式*/
.ant-tabs-nav-container {
  margin-top: 4px;
}
/* 修改 ant-tabs 样式 */
.tab-layout-tabs.ant-tabs {
  border-bottom: 1px solid #ccc;
  border-left: 1px solid #ccc;
  background-color: white;
  padding: 0 20px;

  .ant-tabs-bar {
    margin: 4px 0 0;
    border: none;
  }

  &.ant-tabs-card .ant-tabs-tab{
    padding: 0 16px !important;
    background-color: white !important;
    margin-right: 8px !important;
  } 
}

.ant-tabs {
  &.ant-tabs-card .ant-tabs-card-bar .ant-tabs-tab-active {
    padding-bottom: 1px;
    color: #1890ff;
    background: #fff;
    border-color: #e8e8e8;
    padding: 0px 16px !important;
  }

  &.ant-tabs-card .ant-tabs-tab {

    padding: 0 16px !important;
    background-color: white !important;
    margin-right: 8px !important;

    .ant-tabs-close-x {
      width: 12px !important;
      height: 12px !important;
      opacity: 0 !important;
      cursor: pointer !important;
      font-size: 12px !important;
      margin: 0 !important;
      position: absolute;
      top: 36%;
      right: 6px;
    }

    &:hover .ant-tabs-close-x {
      opacity: 1 !important;
    }
  }
}
.ant-tabs.ant-tabs-card > .ant-tabs-bar {
  .ant-tabs-tab {
    border: none !important;
    border-bottom: 1px solid transparent !important;
  }
  .ant-tabs-tab-active {
    border-color: #1890ff !important;
  }
}
</style>
